package com.gitee.wsl.android.ui.ext

import android.annotation.SuppressLint
import android.app.Activity
import android.content.ClipData
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.text.TextUtils
import androidx.core.app.ShareCompat
import com.gitee.wsl.android.ext.store.*
import com.gitee.wsl.android.ext.store.PathExt.cacheFilePath
import com.gitee.wsl.jvm.ext.store.createAndWrite
import timber.log.Timber

class Share(val activity: Activity) {
    fun shareText(content: String, title: String? = null) =
        share("text/plain") {
            setText(content)
            setChooserTitle(title)
        }

    fun shareImage(imageUri: Uri, title: String? = null) =
        shareTextAndImage(null, imageUri, title)

    fun shareImages(imageUris: List<Uri>, title: String? = null) =
        shareTextAndImages(null, imageUris, title)

    fun shareTextAndImage(content: String?, imageUri: Uri, title: String? = null) =
        share("image/*") {
            setText(content)
            setStream(imageUri)
            setChooserTitle(title)
        }

    fun shareTextAndImages(content: String?, imageUris: List<Uri>, title: String? = null) =
        share("image/*") {
            setText(content)
            imageUris.forEach { addStream(it) }
            setChooserTitle(title)
        }

    fun shareFile(uri: Uri, title: String? = null, mimeType: String = uri.mimeType.orEmpty()) =
        share(mimeType) {
            setStream(uri)
            setChooserTitle(title)
        }

    fun shareFiles(uris: List<Uri>, title: String? = null, mimeType: String? = null) =
        share(mimeType ?: uris.firstOrNull()?.mimeType) {
            uris.forEach { addStream(it) }
            setChooserTitle(title)
        }

    fun shareAsFile(content: String,fileName: String, intentTitle: String, intentSubject: String, clipDataLabel: String){
        val cacheFile = cacheFilePath(fileName)
        if(!cacheFile.createAndWrite(content)){
            Timber.d("shareAsFile create file:$fileName false")
            return
        }
        val uri = cacheFile.getAppUri()

        val shareIntent = ShareCompat.IntentBuilder(activity)
            .setType(activity.contentResolver.getType(uri))
            .setChooserTitle(intentTitle)
            .setSubject(intentSubject)
            .setStream(uri)
            .intent
        shareIntent.apply {
            clipData = ClipData.newRawUri(clipDataLabel, uri)
            addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
        }
        Intent.createChooser(shareIntent, intentTitle)
    }

    inline fun share( mimeType: String?, crossinline block: ShareCompat.IntentBuilder.() -> Unit) =
        ShareCompat.IntentBuilder(activity).setType(mimeType).apply(block).startChooser()

    /**
     * 分享到微信好友
     */
    fun shareTextToWeChat( text: String) {
        //判断是否安装微信，如果没有安装微信 又没有判断就直达微信分享是会挂掉的
        if (!isAppInstall("com.tencent.mm")) {
            activity.toastError( "您还没有安装微信")
            return
        }
        shareText(text, "com.tencent.mm", "com.tencent.mm.ui.tools.ShareImgUI")
    }

    fun shareText(text: String, pkg: String, cls: String) {
        if (TextUtils.isEmpty(text)) {
            activity.toastError("内容不能为空")
            return
        }

        try {
            val intent = Intent()
            intent.component = ComponentName(pkg, cls)
            intent.action = Intent.ACTION_SEND
            intent.putExtra(Intent.EXTRA_TEXT, text)
            intent.type = "text/plain"
            activity.startActivity(Intent.createChooser(intent, "分享"))
        }catch (e: Exception) {
            e.printStackTrace()
            activity.toastError("分享失败")
        }
    }

    @SuppressLint("QueryPermissionsNeeded")
    fun isAppInstall(appPackageName: String): Boolean {
        val packageManager = activity.packageManager // 获取packagemanager
        val info = packageManager.getInstalledPackages(0) // 获取所有已安装程序的包信息
        for (i in info.indices) {
            val pn = info[i].packageName
            if (appPackageName == pn) {
                return true
            }
        }
        return false
    }

    /**
     * 分享到微信朋友圈，需要带一张图
     */
     fun shareTextToWeChatFriend(message: Message) {
        if (!isAppInstall( "com.tencent.mm")) {
            activity.toastError("您还没有安装微信")
            return
        }

        try {
            val intent = Intent()
            intent.component = ComponentName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareToTimeLineUI")
            intent.action = Intent.ACTION_SEND
            intent.type = "image/*";

            val shareStr = """
                ${message.title}
                ${message.description}
                ${message.shareUrl}
                """.trimIndent()
            intent.putExtra(Intent.EXTRA_TEXT, shareStr)
            intent.putExtra("Kdescription", shareStr);
            // 给目标应用一个临时授权，好像用不到
            // intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            intent.putExtra(Intent.EXTRA_STREAM, message.thumbnail);

            activity.startActivity(Intent.createChooser(intent, "分享"))
        }catch (e: Exception) {
            e.printStackTrace()
            activity.toastError("分享失败")
        }
    }

    data class Message(
        var title: String = "",
        var description: String = "",
        var shareUrl: String = "",
        var scene: String = "",
        var thumbnail: Uri? = null)

    fun shareToWeibo(message: Message) {
        if (!isAppInstall( "com.sina.weibo")) {
            activity.toastError( "weibo is not install")
            return
        }

        try {
            val intent = Intent()
            intent.component = ComponentName("com.sina.weibo", "com.sina.weibo.composerinde.ComposerDispatchActivity")
            intent.action = Intent.ACTION_SEND
            intent.type = "image/*";

            val shareStr = """
            ${message.title}
            ${message.description}
            ${message.shareUrl}
            """.trimIndent()
            intent.putExtra(Intent.EXTRA_TEXT, shareStr)
            intent.putExtra(Intent.EXTRA_STREAM, message.thumbnail);

            activity.startActivity(Intent.createChooser(intent, "分享"))
        }catch (e: Exception) {
            e.printStackTrace()
            activity.toastError( "分享失败")
        }
    }

    fun shareToWeibo( text: String) {
        if (!isAppInstall("com.sina.weibo")) {
            activity.toastError( "weibo is not install")
            return
        }
        shareText( text, "com.sina.weibo", "com.sina.weibo.composerinde.ComposerDispatchActivity")
    }

    fun shareToQQ( text: String) {
        if (!isAppInstall( "com.tencent.mobileqq")) {
            activity.toastError("您还没有安装QQ")
            return
        }
        shareText(text, "com.tencent.mobileqq", "com.tencent.mobileqq.activity.JumpActivity")

    }

    fun shareToQzone(context: Context, text: String) {
        if (!isAppInstall( "com.qzone")) {
            context.toastError( "您还没有安装QQ空间")
            return
        }
        shareText(text, "com.qzone", "com.qzonex.module.operation.ui.QZonePublishMoodActivity")

    }

}

val Activity.shareManager: Share
    get() = Share(this)
